'use client'
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { User, Calendar } from 'lucide-react';
import { Button } from './ui/button';
import { Separator } from './ui/separator';
import { getArticleComments, PaginatedResponse } from '../services/commentService';
import { Comment } from '../types/comment';
import { toast } from 'sonner';

interface CommentListProps {
  articleId: string;
  onCommentsUpdated?: () => void;
}

// 定义暴露给父组件的方法
interface CommentListRef {
  refreshComments: () => void;
  addComment: (comment: Comment) => void;
}

const CommentListComponent = ({
  articleId,
  onCommentsUpdated
}: CommentListProps, ref: React.Ref<CommentListRef>) => {
  const [comments, setComments] = useState<Comment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [error, setError] = useState('');
  const [totalComments, setTotalComments] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMoreComments, setHasMoreComments] = useState(false);
  
  // 检查用户是否已登录
  const isLoggedIn = !!localStorage.getItem('auth_token');

  // 加载评论列表
  const loadComments = async (page: number = 1, append: boolean = false) => {
    if (append) {
      setIsLoadingMore(true);
    } else {
      setIsLoading(true);
    }
    setError('');
    
    try {
      const response: PaginatedResponse<Comment> = await getArticleComments(articleId, page);
      console.log('获取到的评论:', response);
      // 确保response.items存在
      const items = response?.items || [];
      
      // 如果是追加模式，则合并评论；否则替换评论
      if (append) {
        setComments(prevComments => [...(prevComments || []), ...items]);
      } else {
        setComments(items);
      }
      
      setTotalComments(response.total || 0);
      setCurrentPage(response.page || 1);
      setHasMoreComments(response.hasMore || false);
    } catch (err) {
      // 在模拟环境中，返回模拟数据
      console.log('评论获取失败!');
      toast.success('评论获取失败!');
    } finally {
      if (append) {
        setIsLoadingMore(false);
      } else {
        setIsLoading(false);
      }
    }
  };

  useEffect(() => {
    loadComments(1, false); // 重置为第一页
  }, [articleId]);

  // 处理评论更新（用于从父组件触发刷新）
  useEffect(() => {
    if (onCommentsUpdated) {
      // 这里只是为了监听父组件的更新信号
      // 实际刷新逻辑在loadComments函数中
    }
  }, [onCommentsUpdated]);



  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
    
    if (diffInSeconds < 60) {
      return '刚刚';
    } else if (diffInSeconds < 3600) {
      return `${Math.floor(diffInSeconds / 60)}分钟前`;
    } else if (diffInSeconds < 86400) {
      return `${Math.floor(diffInSeconds / 3600)}小时前`;
    } else if (diffInSeconds < 604800) {
      return `${Math.floor(diffInSeconds / 86400)}天前`;
    } else {
      return date.toLocaleDateString('zh-CN');
    }
  };

  // 重新加载评论（供父组件调用）
  const refreshComments = () => {
    loadComments(1, false); // 重置为第一页
  };
  
  // 添加新评论到列表开头（供父组件调用）
  const addComment = (comment: Comment) => {
    // 将新评论添加到列表开头
    setComments(prevComments => [comment, ...prevComments]);
    // 更新评论总数
    setTotalComments(prevTotal => prevTotal + 1);
  };
  
  // 加载更多评论
  const loadMoreComments = () => {
    if (!isLoadingMore && hasMoreComments) {
      loadComments(currentPage + 1, true);
    }
  };

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    refreshComments,
    addComment
  }));

  return (
    <div className="comment-list bg-white p-6 rounded-lg shadow-sm">
      <h3 className="text-xl font-semibold mb-6">评论 ({totalComments})</h3>
      
      {isLoading ? (
        <div className="flex justify-center py-8">
          <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-blue-600"></div>
        </div>
      ) : error ? (
        <div className="text-center py-8 text-gray-500">
          <p>{error}</p>
          <Button variant="ghost" onClick={() => loadComments()} className="mt-4">
            重试
          </Button>
        </div>
      ) : !comments || comments.length === 0 ? (
        <div className="text-center py-12 text-gray-500">
          暂无评论，来发表第一条评论吧！
        </div>
      ) : (
        <>
          <div className="space-y-6">
            {comments.map((comment) => (
              <div key={comment.id} className="comment-item">
                <div className="flex items-start gap-4">
                  {/* 用户头像占位 */}
                  <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                    {/* <User className="w-5 h-5 text-blue-600" /> */}
                    <img
                      src={comment.author.avatar}
                      alt={comment.author.username}
                      className="w-full h-full rounded-full object-cover"
                    />
                  </div>
                  
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-1">
                        <span className="font-medium text-gray-900">{comment.author.username}</span>
                        <span className="text-xs text-gray-500 flex items-center gap-1">
                          <Calendar className="w-3 h-3" />
                          {formatDate(comment.createdAt)}
                        </span>
                      </div>
                    
                    <p className="text-gray-700 mb-3">{comment.content}</p>
                  </div>
                </div>
                <Separator className="mt-4" />
              </div>
            ))}
          </div>
          
          {/* 加载更多按钮 */}
          {hasMoreComments && (
            <div className="mt-8 relative flex items-center justify-center py-8">
              {isLoadingMore ? (
                <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              ) : (
                <>
                  <div className="absolute inset-0 flex items-center">
                    <div className="h-px w-full bg-gray-200"></div>
                  </div>
                  <a 
                    href="#" 
                    onClick={(e) => {
                      e.preventDefault();
                      loadMoreComments();
                    }}
                    className="relative px-8 py-1 text-gray-600 text-xs hover:text-blue-600 hover:underline transition-colors duration-300 focus:outline-none"
                  >
                    加载更多评论
                  </a>
                </>
              )}
            </div>
          )}
          
          {/* 显示当前页码信息 */}
          {comments.length > 0 && (
            <div className="mt-4 text-center text-sm text-gray-500">
              显示第 {currentPage} 页，共 {Math.ceil(totalComments / 10)} 页
            </div>
          )}
        </>
      )}
    </div>
  );
};

// 创建forwardRef组件
// 导出组件和类型
export type { CommentListRef };
export default forwardRef<CommentListRef, CommentListProps>(CommentListComponent);